package com.erp.action;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;

import com.erp.dto.Page;
import com.erp.dto.User;
import com.erp.util.CommonUtils;
import com.erp.util.DepartmentUtils;

@SuppressWarnings("serial")
@Controller(value = "userAction")
@Scope(value = "prototype")
public class UserAction extends ModelDrivenBaseAction<User> {

	// 判断密码是否已加密（默认没有加密）
	private boolean encodedPWD = false;

	private Integer[] roleIds;
	private String ifSave;

	public Integer[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(Integer[] roleIds) {
		this.roleIds = roleIds;
	}

	public String getIfSave() {
		return ifSave;
	}

	public void setIfSave(String ifSave) {
		this.ifSave = ifSave;
	}

	/**
	 * 添加页面
	 */
	public String addPage() throws Exception {
		request.put("departmentList",
				DepartmentUtils.getDepartmentTree(departmentService.listAll()));
		request.put("roleList", roleService.listAll());
		return "addPage";
	}

	/**
	 * 添加操作
	 */
	public void add() throws Exception {
		model.setRoles(roleService.getRoleListByArray(roleIds));
		model.setPassword(DigestUtils.md5DigestAsHex("12345".getBytes()));
		userService.add(model, true);
		writeJson("msg", "true");
	}

	/**
	 * 删除操作
	 */
	public void delete() throws Exception {
		userService.delete(model);
		writeJson("msg", "true");
	}

	/**
	 * 编辑页面
	 */
	public String editPage() throws Exception {
		request.put("departmentList",
				DepartmentUtils.getDepartmentTree(departmentService.listAll()));
		request.put("roleList", roleService.listAll());
		model = userService.getUserById(model.getId());
		pushIntoValueStack(model);
		return "editPage";
	}

	/**
	 * 编辑操作
	 */
	public void edit() throws Exception {
		model.setRoles(roleService.getRoleListByArray(roleIds));
		userService.update(model, true);
		writeJson("msg", "true");
	}

	/**
	 * 确认是本人操作
	 */
	public void checkPassword() throws Exception {
		String realPassword = ((User) session.get("user")).getPassword();
		String inputPassword = CommonUtils.generateMd5(model.getPassword());
		if (inputPassword != null && inputPassword.equals(realPassword)) {
			session.put("myself", true);
			writeJson("msg", "true");
		} else {
			writeJson("msg", "false");
		}
	}

	/**
	 * 修改密码操作
	 */
	public void modifyPassword() throws Exception {
		Boolean isMyself = (Boolean) session.get("myself");
		User user = (User) session.get("user");
		if (isMyself != null && isMyself == true) {
			model.setId(user.getId());
			user.setPassword(userService.midifyPassword(model));
			writeJson("msg", "true");
		} else {
			writeJson("msg", "false");
		}
	}

	/**
	 * 修改密码页面
	 */
	public String modifyPasswordPage() throws Exception {
		return "modifyPasswordPage";
	}

	/**
	 * 初始化为默认密码
	 */
	public void initPassword() throws Exception {
		String password = userService.initPassword(model);
		User user = (User) session.get("user");
		if (user.getId() == model.getId()) {
			user.setPassword(password);
			session.put("user", user);
		}
		writeJson("msg", "true");
	}

	/**
	 * 登录页面
	 */
	public String loginPage() throws Exception {
		String toPage = getUserFromCookies();
		if (toPage != null) {
			return toPage;
		} else
			return "loginPage";
	}

	/**
	 * 从cookie获取解码后用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	private String getUserFromCookies() throws Exception {
		String toPage = null;
		Cookie[] cookies = getRealReq().getCookies();
		if (cookies != null) {
			String name = null;
			String password = null;
			for (Cookie cookie : cookies) {
				if ("SESSION_LOGIN_USERNAME".equals(cookie.getName())) {
					name = CommonUtils.decodeBase64(cookie.getValue());// 将得到cookie的用户名Base64解码
				}
				if ("SESSION_LOGIN_PASSWORD".equals(cookie.getName())) {
					password = CommonUtils.decodeBase64(cookie.getValue()); // 将得到cookie的密码Base64解码
				}

			}
			if(name==null||password == null||name.isEmpty()||password.isEmpty()){
				return null;
			}else {
				model = new User();
				model.setName(name);
				model.setPassword(password);
				// 设置密码为已加密
				this.encodedPWD = true;
				toPage = login();
			}
		}
		return toPage;
	}

	/**
	 * 登录操作
	 */
	public String login() throws Exception {
		User user = null;
		if (model != null) {
			model.setLoginTime(new Date());
			model.setIp(getClientIp(getRealReq()));
			// TODO 手动设置IP
			// model.setIp("115.231.49.46");
			user = userService.login(model, encodedPWD);
		}
		if (user != null) {

			if ("save".equals(ifSave)) {
				HttpServletResponse response = getRealResp();

				Cookie cookie = null;
				// cookie写入中文会报错，先用URLEncode或Base64之类的编码
				cookie = new Cookie("SESSION_LOGIN_USERNAME",
						CommonUtils.encodeBase64(user.getName()));
				// 设置过期时间三天
				cookie.setMaxAge(3 * 24 * 60 * 60);
				// TODO 设置路径，这个路径即该工程下都可以访问该cookie
				// cookie.setPath("/"); // 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
				// TODO 单点登录的跨域问题
				// cookie.setDomain("");
				response.addCookie(cookie);

				cookie = new Cookie("SESSION_LOGIN_PASSWORD",
						CommonUtils.encodeBase64(user.getPassword()));
				cookie.setMaxAge(3 * 24 * 60 * 60);
				response.addCookie(cookie);
			}

			session.put("user", user);
			session.put("userPrivilegeList",
					userService.getUserPrivilege(user.getRoles()));
			return "toIndex";
		} else {
			// TODO 登录失败，清除cookie和session
			removeAllCookies();
			addFieldError("error", "用户名或密码错误！");
			return "loginPage";
		}
	}

	/**
	 * 移除所有Cookies
	 */
	private void removeAllCookies() {
		Cookie[] cookies = getRealReq().getCookies();
		if (cookies != null) {
			HttpServletResponse response = getRealResp();
			for (Cookie cookie : cookies) {
				cookie.setValue(null);
				response.addCookie(cookie);
			}
		}
	}

	/**
	 * 获取远程客户端真实IP
	 * 
	 * @param request
	 * @return
	 */
	private String getClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 注销操作
	 */
	public String logout() throws Exception {
		removeAllCookies();
		session.remove("user");
		return "logoutPage";
	}

	public String list() throws Exception {
		if (page == null) {
			page = new Page();
		}
		return pagedList();
	}

	/**
	 * 所有用户列表
	 */
	public String listAll() throws Exception {
		request.put("userList", userService.listAll());
		return "list";
	}

	/**
	 * 分页后的用户列表
	 */
	public String pagedList() throws Exception {
		request.put("userList", userService.getPagedList(page));
		pushIntoValueStack(page);
		return "list";
	}

	public String query() throws Exception {

		return "";
	}

	public String show() throws Exception {
		pushIntoValueStack(userService.getUserById(model.getId()));
		return "summary";
	}

}
